package edu.wichita.weighin;

import java.io.FileOutputStream;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;

public class SaveWeightDialogFragment extends DialogFragment {

    String weightFileName = "storedweights";
    FileOutputStream outputStream = null;
    Context context;

    public static SaveWeightDialogFragment newInstance(float weightFloat) {
        SaveWeightDialogFragment frag = new SaveWeightDialogFragment();
        Bundle args = new Bundle();
        args.putFloat("weightFloat", weightFloat);
        frag.setArguments(args);
        return frag;
    }
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        final float weightFloat = getArguments().getFloat("weightFloat");
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setMessage("Save Weight").setPositiveButton("Save", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // save weight
                System.out.println(weightFloat);
                try {
                    outputStream = getActivity().openFileOutput(weightFileName, Context.MODE_APPEND);
                    String asFloatString = Float.toString(weightFloat)+"\n";
                    outputStream.write(asFloatString.getBytes());
                    outputStream.flush();
                    outputStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // cancel the dialogue and do not save the weight
                SaveWeightDialogFragment.this.getDialog().cancel();
            }
        });
    return builder.create();
    }
}